package seckill

import (
	"context"
	"encoding/json"
	"mall/app/seckill/cmd/api/global_key"
	"mall/app/seckill/cmd/api/internal/types"
	"strconv"
	"strings"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
	"mall/app/seckill/cmd/api/internal/svc"
)

type GetCurrentSeckillSkusLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetCurrentSeckillSkusLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCurrentSeckillSkusLogic {
	return &GetCurrentSeckillSkusLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetCurrentSeckillSkusLogic) GetCurrentSeckillSkus() ([]types.SeckillSkuRedisTo, error) {
	now := time.Now().Unix()
	keys, err := l.svcCtx.RedisClient.Keys(global_key.SessionsCachePrefix + "*")
	if err != nil {
		l.Error(err)
		return nil, err
	}
	l.Error("lsz::", keys)
	for _, key := range keys {
		pair := strings.ReplaceAll(key, global_key.SessionsCachePrefix, "")
		times := strings.Split(pair, "_")
		startTime, _ := strconv.ParseInt(times[0], 10, 64)
		endTime, _ := strconv.ParseInt(times[1], 10, 64)
		l.Error(startTime, now, endTime)
		if now >= startTime && now < endTime {
			r, err := l.svcCtx.RedisClient.Lrange(key, 0, -1)
			if err != nil {
				l.Error(err)
				return nil, err
			}
			list, err := l.svcCtx.RedisClient.Hmget(global_key.SkukillCacheKey, r...)
			if err != nil {
				l.Error(err)
				return nil, err
			}
			var redisTos []types.SeckillSkuRedisTo

			if len(list) > 0 {
				for _, skuInfo := range list {
					to := types.SeckillSkuRedisTo{}
					err := json.Unmarshal([]byte(skuInfo), &to)
					if err != nil {
						l.Error(err)
						return nil, err
					}
					redisTos = append(redisTos, to)
				}
			}
			return redisTos, nil
		}
	}
	return nil, err
}
